package com.housekeeperapp;

import android.app.Activity;
//<<<<<<< HEAD
import android.app.Application;
import android.app.Dialog;
//=======
//>>>>>>> master-temp
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;


import androidx.annotation.NonNull;
import androidx.multidex.MultiDex;

import com.RNFetchBlob.RNFetchBlobPackage;
import com.component.amap.RCTAMapPackage;
import com.component.chat.EasemobChatPackage;
import com.component.common.UtilsPackage;
import com.component.imagepicker.PickerPackage;
import com.component.socketio.SocketIoPackage;
import com.easemob.helpdesk.IMHelper;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.listener.HKActivityLifecycleCallbacks;
import com.easemob.helpdesk.utils.PreferenceUtils;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import com.heyao216.react_native_installapk.InstallApkPackager;
import com.housekeeperapp.opensettings.OpenSettingsPackage;
import com.housekeeperapp.persistence.SharedPreferencesPackage;
import com.hyphenate.kefusdk.HDEventListener;
import com.hyphenate.kefusdk.chat.HDClient;
import com.hyphenate.kefusdk.manager.session.CurrentSessionManager;
import com.imagepicker.ImagePickerPackage;

import com.liyuzhao.badger.BadgeUtil;
import com.reactnativecomponent.amaplocation.RCTAMapLocationPackage;
import com.reactnativecomponent.swiperefreshlayout.RCTSwipeRefreshLayoutPackage;
import com.reactnativenavigation.NavigationApplication;
import com.rnfs.RNFSPackage;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import cn.jiguang.plugins.push.JPushPackage;


//import io.sentry.RNSentryPackage;

//import com.cboy.rn.splashscreen.SplashScreenReactPackage;

public class MainApplication extends NavigationApplication {

    private boolean SHUTDOWN_TOAST = false;
    private boolean SHUTDOWN_LOG = false;

    private static final String TAG = MainApplication.class.getSimpleName();
    private final List<Activity> activityList = Collections.synchronizedList(new LinkedList<Activity>());

    public static long AgentLastUpdateTime = 0;
    public Bitmap avatarBitmap = null;
    public boolean avatarIsUpdate;

    private static MainApplication instance;
    public Bundle bundle;

    public Dialog loadingDialog = null;

    private Handler mHandler = new Handler();

    private boolean isBroadcastUnreadCount;

    private boolean newMsgNotiStatus;
    private boolean notiAlertSoundStatus;
    private boolean notiAlertVibrateStatus;
    private int mActivityCount = 0;
    private HKActivityLifecycleCallbacks mHkActivityLifecycleCallbacks;
    public boolean isNewCreate = false;
    /**
     * HDEventListener
     */
    private HDEventListener eventListener;

//  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
//    @Override
//    public boolean getUseDeveloperSupport() {
//      return BuildConfig.DEBUG;
//    }
//
//    @Override
//    protected List<ReactPackage> getPackages() {
//      return Arrays.<ReactPackage>asList(
//          new MainReactPackage(),
//            new InstallApkPackager(),
//            new RNFSPackage(),
//            new RNFetchBlobPackage(),
//            new RNFSPackage(),
//      );
//    }
//  };
//
//  @Override
//  public ReactNativeHost getReactNativeHost() {
//    return mReactNativeHost;
//  }

    @Override
    public boolean isDebug() {
    return BuildConfig.DEBUG;
    }

    @NonNull
    @Override
    public List<ReactPackage> createAdditionalReactPackages() {
        // Add the packages you require here.
        // No need to add RnnPackage and MainReactPackage
        return Arrays.<ReactPackage>asList(
//                new ReactNativeConfigPackage(),
                new RCTSwipeRefreshLayoutPackage(),
                new RCTAMapLocationPackage(),
                new RCTAMapPackage(),
                new ImagePickerPackage(),
                new PickerPackage(),
                new SocketIoPackage(),
//                new RNSentryPackage(MainApplication.this),
                new JPushPackage(),
                new EasemobChatPackage(MainApplication.this),
                new OpenSettingsPackage(),
                new RNFetchBlobPackage(),
                new RNFSPackage(),
                new InstallApkPackager(),
                new UtilsPackage(),
                new SharedPreferencesPackage()
        );
    }

    @Override
    public void onCreate() {
        super.onCreate();

//        instance = this;
//        HDClient.getInstance().init(this);
//        HDClient.getInstance().setDebugMode(true);
//        registerEventListener();

        instance = this;
//        HDClient.Options options = new HDClient.Options();
//        options.setMipushConfig("", "");
        //小米推送配置
        isNewCreate = true;
        HDClient.Options options = new HDClient.Options();
        options.setMipushConfig("2882303761517634256","5661763493256");
        HDClient.getInstance().init(this, options);
        CrashReport.initCrashReport(getApplicationContext(), "a3a7856e9a", true);

        PreferenceUtils.getInstance().init(this);
        registerActivityListener();

        //设置lifecycle监听
        mHkActivityLifecycleCallbacks = new HKActivityLifecycleCallbacks(mActivityCount);
        registerActivityLifecycleCallbacks(mHkActivityLifecycleCallbacks);

//        IMHelper.getInstance().setGlobalListener();
        HDClient.getInstance().setDebugMode(BuildConfig.DEBUG);

        isBroadcastUnreadCount = PreferenceUtils.getInstance().getBroadcastUnReadCount();

        newMsgNotiStatus = PreferenceUtils.getInstance().getNewMsgNotiStatus();
        notiAlertSoundStatus = PreferenceUtils.getInstance().getNotiAlertSoundStatus();
        notiAlertVibrateStatus = PreferenceUtils.getInstance().getNotiAlertVibrateStatus();

        SoLoader.init(this, /* native exopackage */ false);

    }

    public int getmActivityCount() {
        mActivityCount = mHkActivityLifecycleCallbacks.getCount();
        return mActivityCount;
    }

    public boolean isNewCreate() {
        return isNewCreate;
    }

    public void setNewCreate(boolean newCreate) {
        isNewCreate = newCreate;
    }

    /**
    * Class Instance Object
    *
    * @return MainApplication
    */
    public static MainApplication getInstance() {
    return instance;
    }

    public void setBroadcastUnreadCount(boolean enable){
        isBroadcastUnreadCount = enable;
        PreferenceUtils.getInstance().setBroadcastUnReadCount(enable);
    }

    public boolean isBroadcastUnreadCount(){
        return isBroadcastUnreadCount;
    }

    public void setNewMsgNotiStatus(boolean newMsgNotiStatus) {
        this.newMsgNotiStatus = newMsgNotiStatus;
        PreferenceUtils.getInstance().setNewMsgNotiStatus(newMsgNotiStatus);
    }

    public void setNotiAlertSoundStatus(boolean notiAlertSoundStatus) {
        this.notiAlertSoundStatus = notiAlertSoundStatus;
        PreferenceUtils.getInstance().setNotiAlertSoundStatus(notiAlertSoundStatus);
    }

    public void setNotiAlertVibrateStatus(boolean notiAlertVibrateStatus) {
        this.notiAlertVibrateStatus = notiAlertVibrateStatus;
        PreferenceUtils.getInstance().setNotiAlertVibrateStatus(notiAlertVibrateStatus);
    }

    public boolean isNewMsgNotiStatus() {
        return PreferenceUtils.getInstance().getNewMsgNotiStatus();
    }

    public boolean isNotiAlertSoundStatus() {
        return PreferenceUtils.getInstance().getNotiAlertSoundStatus();
    }

    public boolean isNotiAlertVibrateStatus() {
        return PreferenceUtils.getInstance().getNotiAlertVibrateStatus();
    }

    public synchronized int getUnReadMsgCount() {
        if(MainActivity.instance.getMsgFragment() != null){
            return MainActivity.instance.getMsgFragment().waitCount + CurrentSessionManager.getInstance().getTotalUnReadCount();
        }else{
            return CurrentSessionManager.getInstance().getTotalUnReadCount();
        }
    }


    /**
     * Save Activity to existing lists
     *
     * @param activity
     */
    public void pushActivity(Activity activity) {
        synchronized (activityList){
            if (!activityList.contains(activity)) {
                activityList.add(activity);
            }
        }
    }

    public void popActivity(Activity activity) {
        synchronized (activityList){
            if (activityList.contains(activity)) {
                activityList.remove(activity);
            }
        }
    }

    public boolean isNoActivity(){
        return activityList.isEmpty();
    }


    public List getActivityList() {
        return activityList;
    }

    /**
     * 获取当前最顶部的activity的实例
     * @return
     */
    public Activity getTopActivity(){
        Activity mBaseActivity;
        synchronized (activityList){
            final int size = activityList.size() - 1;
            if(size < 0){
                return null;
            }
            mBaseActivity = activityList.get(size);
        }
        return mBaseActivity;
    }

    /**
     * 回到首页Activity
     */
    public void gotoMainActivity(){

        synchronized(activityList) {
            final int size = activityList.size() - 1;
            for (int i = size; i >= 0; i--){
                if(activityList.get(i) instanceof MainActivity) {
                    break;
                }else{
                    activityList.get(i).finish();
                }
            }
        }
    }


    /**
     * 结束所有的Activity
     */
    public void finishAllActivity() {
        synchronized (activityList){
            for (Activity activity : activityList) {
                if (activity != null) {
                    if (!activity.isFinishing()) {
                        activity.finish();
                    }
                }
            }
        }
    }


    private void registerActivityListener(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
            registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                    /**
                     * 监听 activity 创建事件 将该activity 加入list
                     */
//                    if(!(activity instanceof LoginActivity)){
//
//                    }

                    pushActivity(activity);

                }

                @Override
                public void onActivityStarted(Activity activity) {

                }

                @Override
                public void onActivityResumed(Activity activity) {

                }

                @Override
                public void onActivityPaused(Activity activity) {

                }

                @Override
                public void onActivityStopped(Activity activity) {

                }

                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

                }

                @Override
                public void onActivityDestroyed(Activity activity) {
                    if (null == activityList || activityList.isEmpty()){
                        return;
                    }

                    if (activityList.contains(activity)){
                        /**
                         * 监听到Activity销毁事件 将该Activity 从list中移除
                         */
                        popActivity(activity);
                    }

                }
            });
        }
    }


    public synchronized void logout() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (avatarBitmap != null && !avatarBitmap.isRecycled()) {
                    avatarBitmap.recycle();
                    avatarBitmap = null;
                }
                try{
                    BadgeUtil.resetBadgeCount(getApplicationContext());
                }catch (Exception e){
                }
            }
        });
    }

    public void exitApp() {
        super.onTerminate();

        try {

            finishAllActivity();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            System.exit(0);
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
